<script setup lang="ts">
import { reactive, ref } from 'vue'

//使用ref实现
const list = ref([
  { id: 1, name: '《红楼梦》', author: '曹雪芹' },
  { id: 2, name: '《西游记》', author: '吴承恩' },
  { id: 3, name: '《水浒传》', author: '施耐庵' },
  { id: 4, name: '《三国演义》', author: '罗贯中' }
])

//定义函数
//根据id来删除
const delItem = (id:number)=> {

  //id 转换为对应的索引 findIndex
  const index =list.value.findIndex(item=>item.id==id)
   // console.log(index)
  // 索引 删除对应的元素 splice
  list.value.splice(index,1)
}


//使用reactive实现
const list2 = reactive([
  { id: 1, name: '《三体》', author: '刘慈欣' },
  { id: 2, name: '《活着》', author: '余华' },
  { id: 3, name: '《撒哈拉的故事》', author: '三毛' },
  { id: 4, name: '《盗墓笔记》', author: '南派三叔' }
])

// 定义函数
// 根据 id 来删除
const delItem2=(id:number) => {
 // id 转换为对应的索引 findIndex
 const index = list2.findIndex(item => item.id == id)
  // console.log(index)
  // 索引 删除对应的元素 splice
  list2.splice(index,1)
}

</script>


<template>
  <div id="app">
    <h3>小黑的书架-reactive</h3>
    <ul>
      <li v-for="item in list2" :key="item.id">
        <span>{{ item.name }}</span>
        <span>{{ item.author }}</span>
        <button @click="delItem2(item.id)">删除</button>
      </li>
    </ul>
    <h3>小黑的书架-ref</h3>
    <ul>
      <li v-for="item in list" :key="item.id">
        <span>{{ item.name }}</span>
        <span>{{ item.author }}</span>
        <button @click="delItem(item.id)">删除</button>
      </li>
    </ul>
  </div>
</template>

<style></style>